"use client";


import { cn } from "@/lib/utils";
import { message } from "antd";
import { result } from "lodash-es";
import { redirect, useRouter } from "next/navigation";
import { useEffect, useState, useOptimistic, useTransition } from "react";
import { userLogin } from "../actions/user_action";

export type LoginProp = {
  name: string;
  password: string;
};
export const dynamic = "force-dynamic";
export default function Login() {
  // 乐观更新，不会阻塞ui渲染
//   const [loading, setLoading] = useState(false);
  const [isPending, startTransition] = useTransition();
  const route = useRouter();

  async function tologin(data: any) {
    const formData = Object.fromEntries(data.entries()) as LoginProp;
    if (!formData.name || !formData.password) {
    //   setLoading(false);
      alert("账号密码不能为空");
      return;
    }

    const result = await userLogin(formData);
    if (result.data) {
      window.location.href = `/admin`;
    } else {
      message.error("用户名密码不正确");
    }
    // setLoading(false);
  }

  return (
    <div className="flex w-[100vw] h-[100vh] items-center justify-center">
      <form
        action={async (data) => {
        //   setLoading(true);
          startTransition( () => {
             tologin(data);
          });
        }}
        className=" shadow-lg p-10"
      >
        <h2 className="text-center my-4 text-4xl font-bold">管理系统</h2>
        <input
          type="text"
          name="name"
          className="border border-gray-300 w-full h-10 px-4 mt-8"
          placeholder="请输入账号"
        />
        <input
          type="password"
          name="password"
          placeholder="请输入密码"
          autoComplete=""
          className="border border-gray-300 w-full h-10 px-4 my-4"
        />
        <button
          type="submit"
          className={cn(
            "bg-blue-500 text-white py-2 w-full rounded-md hover:opacity-75",
            {
              "opacity-30": isPending,
            }
          )}
        >
          {isPending ? "登录中..." : "登录"}
        </button>
      </form>
      {/* <button className=" m-20" onClick={async () => {
        const resultl = await getSwiper()
        console.log(resultl);
      }}>测试</button> */}
    </div>
  );
}
